const express = require('express');
const app = express();
app.listen(3000, () => { console.log('服务器已开启') });

const path = require('path');
const fs = require('fs');
const time = require('time-stamp');
const formidable = require('formidable');
//静态资源化
// app.use('/staic', express.static(path.join(__dirname, 'view/static')))
app.use(express.static(path.join(__dirname, 'view')))


//路由渲染面
app.get('/register', (req, res) => {
    res.sendFile(path.join(__dirname, '/view/register.html'));
})

//post接参中间件
// app.use(express.urlencoded({ extended: true}));
// app.use(express.json());

//自定义中间件  -- 时间
app.use((req, res, next) => {
    req.time = time('YYYY年MM月DD日 HH:mm:ss')
    next();
})
//获取persons.json数据
let dir = path.join(__dirname, 'persons.json');
let data = fs.readFileSync(dir, 'utf-8');
data = JSON.parse(data);

//登录逻辑
app.post('/register', (req, res, next) => {
    //获取数据
    // let { tel, pass, pass2} = req.body;
    // console.log(tel, pass, pass2);
    //上传图片
    let form = formidable({
        uploadDir: path.join(__dirname, 'upload'), //指定上传的文件存放位置
        keepExtensions: true // 是否保留上传后文件的后缀
    })

    // 将请求消息中携带的参数解析出来
    form.parse(req, (err, fileds, files) => {
        console.log(err, fileds, files);
        // err错误    fileds 获取普通输入框内容    files上传的文件信息
        if (err) {
            res.send(err)
        } else {

            res.send('上传成功')
        }
        let s = data.find(item => item.username == fileds.username);

        if (s) {
            res.send('用户已存在');
            return;
        }
        let newpath = path.join('upload', files.photo.originalFilename);
        let time= req.time;
        //注册
        data.push({ fileds, time, newpath })
        fs.writeFileSync(dir, JSON.stringify(data));
        res.send({ code: 200, msg: "注册成功" })

    })





})

//统一处理错误
app.use((err, req, res, next) => {
    res.send({ code: 400, msg: err })
})



